// 通用方法
import { isPlainObject, isString, round } from 'lodash';

/**
 * 排除数据为空字符或null或undefined的数据
 * @param data
 * @returns
 */
export const excludeEmpty = <T extends Record<string, any>>(data: T) => {
  const obj: Record<string, any> = {};
  if (isPlainObject(data)) {
    Object.keys(data).forEach(key => {
      const element = data[key];
      if (isString(element) && element.trim() !== '') {
        obj[key] = element as any;
      } else if (element || element === 0) {
        obj[key] = element;
      }
    });
  }
  return obj;
};

/**
 * 是MAC设备
 */
export function isMac() {
  return (
    !import.meta.env.SSR && /macintosh|mac os x/i.test(navigator.userAgent)
  );
}

/**
 * 是Firefox浏览器
 */
export function isFirefox() {
  return (
    typeof navigator !== 'undefined' &&
    navigator.userAgent.toLowerCase().indexOf('firefox') > -1
  );
}

/**
 * 文件转链接
 * @param file
 * @returns 预览链接
 */
export function getObjectURL(file: File | Blob) {
  let url = '';

  if ((window as any).createObjectURL !== undefined) {
    url = (window as any).createObjectURL(file);
  } else if (window.URL !== undefined) {
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL !== undefined) {
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

/**
 * 销毁createObjectURL
 * @param objectURL
 */

export function removeObjectURL(objectURL: string) {
  if (/^blob:/.test(objectURL)) {
    if ((window as any).revokeObjectURL !== undefined) {
      (window as any).revokeObjectURL(objectURL);
    } else if (window.URL !== undefined) {
      window.URL.revokeObjectURL(objectURL);
    } else if (window.webkitURL !== undefined) {
      window.webkitURL.revokeObjectURL(objectURL);
    }
  }
}

/**
 * Byte转化为数值单位KB/MB/GB
 * @param Byte
 * @param precision 保留小数位
 * @returns
 */
export function getByteToStr(Byte: number, precision = 0) {
  let GB = 0;
  let MB = 0;
  let KB = 0;
  const B = Byte;
  KB = round(B / 1024, precision);
  if (KB >= 1024) {
    MB = round(B / 1024 / 1024, precision);
    if (MB >= 1024) {
      GB = round(B / 1024 / 1024 / 1024, precision);
    }
  }
  if (GB) {
    return `${GB} GB`;
  }
  return MB ? `${MB} MB` : `${KB} KB`;
}
